// APP参数
window.APP = {
	app_name: '龙信云商铺',
	version_name: '1.0',
	web_root: "http://z2.com/",
	api_url: "http://taigu.cn/api/",
	pic_url: "http://taigu.cn/",
	//web_root: "http://test.ilong3.cn/",
	//api_url: "http://test.ilong3.cn/api/",
	//web_root: "http://a2.ilong3.cn/",
	//api_url: "http://test.ilong3.cn/api/",
	payment: {
		ALIPAY: 3,
		WECHAT: 2,
		UNIONPAY: 4,
		YUE: 1
	}
}
Date.prototype.Format = function(fmt)   
	{ //author: meizz   
	  var o = {   
	    "M+" : this.getMonth()+1,                 //月份   
	    "d+" : this.getDate(),                    //日   
	    "h+" : this.getHours(),                   //小时   
	    "m+" : this.getMinutes(),                 //分   
	    "s+" : this.getSeconds(),                 //秒   
	    "q+" : Math.floor((this.getMonth()+3)/3), //季度   
	    "S"  : this.getMilliseconds()             //毫秒   
	  };   
	  if(/(y+)/.test(fmt))   
	    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));   
	  for(var k in o)   
	    if(new RegExp("("+ k +")").test(fmt))   
	  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));   
	  return fmt;   
} 
//生成单号
function getSn(){
	var time1 = new Date().Format("yyyyMMddhhmmss");
	var num = Math.random(); //生成0-1的随机码。
	num = Math.round(num * 1e8); //扩大10的8次方倍后取整。
	var sn=time1.toString() + num;
	return sn;
}
function getOpenId() {
	var iswx = is_weixn();
	var access_code = getQueryString("code");
	var member = localStorage.getItem("member");
	var openid = getcookie("openid");
	if(iswx && openid == "" && member != null) {
		if(access_code == null) {
			var fromurl = location.href;
			var url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxa8273be4e9212fe1&redirect_uri=' + encodeURIComponent(fromurl) + '&response_type=code&scope=snsapi_base&state=STATE%23wechat_redirect&connect_redirect=1#wechat_redirect';
			location.href = url;
		} else {
			var member = JSON.parse(member);
			if(member["openid"] != null && member['openid'] != "") {
				console.log(member["openid"]);
				addcookie("openid", member['openid']);
			} else {
				$.ajax({
					type: 'post',
					url: APP.api_url + 'Member/getOpenId',
					data: {
						code: access_code,
						uid: getUid(),
						token: member['token']
					},
					success: function(data) {
						var res = JSON.parse(data);
						if(res.code != 200) {
							layer.msg(res.msg);
							return;
						}
						member['openid'] = res.data;
						localStorage.setItem("member", JSON.stringify(member));
						addcookie("openid", data);
					}
				});
			}
		}
	}

}
//判断是否是微信
function is_weixn() {
	var ua = navigator.userAgent.toLowerCase();
	if(ua.match(/MicroMessenger/i) == "micromessenger") {
		return true;
	} else {
		return false;
	}
}

function getQueryString(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	var r = window.location.search.substr(1).match(reg);
	if(r != null) return unescape(r[2]);
	return null;
}
// 退出用户
function logout() {
	localStorage.removeItem("member");
	window.location.href = "../login.html";
}
// 增加cookie
function addcookie(name, value, expireHours) {
	var cookieString = name + "=" + escape(value) + "; path=/";
	//判断是否设置过期时间  
	if(expireHours > 0) {
		var date = new Date();
		date.setTime(date.getTime + expireHours * 3600 * 1000);
		cookieString = cookieString + "; expire=" + date.toGMTString();
	}
	document.cookie = cookieString;
}
// 获得cookie
function getcookie(name) {
	var strcookie = document.cookie;
	var arrcookie = strcookie.split("; ");
	for(var i = 0; i < arrcookie.length; i++) {
		var arr = arrcookie[i].split("=");
		if(arr[0] == name) return decodeURIComponent(arr[1]); //增加对特殊字符的解析  
	}
	return "";
}
//订单状态：1：未付款；2：拼团中；3：待发货；4：已发货；5：已完成；6：已关闭7:待确认消费8物流不达9交易完成10管理员关闭11客户关闭12点参待消费13点餐确认消费14点餐预约
function getOrderStatus(order_state){
	var status="";
	switch(order_state){
		case 1:status= "未付款";break;
		case 2:status= "拼团中";break;
		case 3:status= "待发货";break;
		case 4:status= "已发货";break;
		case 5:status= "已完成";break;
		case 6:status= "已关闭";break;
		case 7:status= "待确认消费";break;
		case 8:status= "物流不达";break;
		case 9:status= "交易完成";break;
		case 10:status= "系统关闭";break;
		case 11:status= "用户关闭";break;
		case 12:status= "待付款";break;//点餐
		case 13:status= "待确认消费";break;//点餐
		case 14:status= "待付款";break;//预约
		case 15:status= "待确认消费";break;//预约
		defatult:
		status="未付款";
	}
	return status;
}
// 删除cookie
function delCookie(name) { //删除cookie  
	var exp = new Date();
	exp.setTime(exp.getTime() - 1);
	var cval = getcookie(name);
	if(cval != null) document.cookie = name + "=" + cval + "; path=/;expires=" + exp.toGMTString();
}
//获取用户当前地址
function get_user_Axis(){
	var script = document.createElement("script");
	script.type = "text/javascript";
	script.src = "http://api.map.baidu.com/api?v=2.0&ak=grTHl4v1H6uGFLChfz0aB0uQG4XWQv0k&callback=getAxis";
	document.body.appendChild(script);
	
	return  JSON.parse(localStorage.getItem('axis'));
}

function getAddress(){
	Axis = new Object();
	Axis.longitude = 113.026533;
	Axis.latitude = 25.80212;
	if (navigator.geolocation) {  //调用导航器geolocation函数
        navigator.geolocation.getCurrentPosition(function(position){
        	var lat = position.coords.latitude;//y，纬度，
			var lon = position.coords.longitude;//x，经度
			Axis.longitude = lat;
			Axis.latitude = lon;
		    var map = new BMap.Map("container"); //初始化地图类
		    var point = new BMap.Point(lon,lat); //这里设置刚开始的点所在处
		    var gc = new BMap.Geocoder();  //初始化，Geocoder类
			gc.getLocation(point, function (rs) {
				  var addComp = rs.addressComponents;
			      var province = addComp.province;//获取省份
			      var city = addComp.city;//获取城市
			      var district = addComp.district;//区
			      var street = addComp.street;//街
			      $("#address").text(district+street);
   			}); //进入总显示函数loand，函数名由自己定
     });
    } else {
         alert("您的浏览器不支持地理定位");//不支持
    }
    localStorage.setItem('axis', JSON.stringify(Axis));
}
// 底部导航 
function get_cut_foot(type, index) {
	if(type == "sj") {
		getsjFoot(index);
	} else if(type == "zh") {
		getlmFoot(index);
	} else {
		getFoot(index)
	}
}
//获取底部导航
function get_navigation(){
	var navigation =  getcookie("navigation");
	if(navigation == 'sj'){
		getsjFoot(getUrlParam("foot_active") > 0 ? getUrlParam("foot_active") : 2);
	}else if(navigation == 'lm'){
		getlmFoot(getUrlParam("foot_active") > 0 ? getUrlParam("foot_active") : 2);
	}else{
		getFoot(getUrlParam("foot_active") > 0 ? getUrlParam("foot_active") : 2);
	}
}
function getRootPath_web() {
            //获取当前网址，如： http://localhost:8083/uimcardprj/share/meun.jsp
            var curWwwPath = window.document.location.href;
            //获取主机地址之后的目录，如： uimcardprj/share/meun.jsp
            var pathName = window.document.location.pathname;
            var pos = curWwwPath.indexOf(pathName);
            //获取主机地址，如： http://localhost:8083
            var localhostPaht = curWwwPath.substring(0, pos);
            //获取带"/"的项目名，如：/uimcardprj
            var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
            return localhostPaht;
        }
// 综合商城菜单
function getFoot(chai) {
	var path=getRootPath_web();
	var typeid=getUrlParam("type");
	var shouye="index.html?foot_active=2";
	if((typeid!='null')&&(typeid!=undefined)){
		shouye="shop.html?type="+typeid;
	}
	$("#footer").html('<nav class="mui-bar mui-bar-tab">' +
		'<a id="cut_cd_1" class="mui-tab-item"  href="'+APP.web_root+'index.html?foot_active=1">' +
		'<i class="mui-icon iconfont icon-icon-shouyeshouye"></i>' +
		'<span class="mui-tab-label">首页</span>' +
		'</a>' +
		'<a id="cut_cd_2" class="mui-tab-item"  href="'+APP.web_root+'shop/shoplist.html?foot_active=2">' +
		'<i class="mui-icon iconfont icon-1230shengchanzhe"></i>' +
		'<span class="mui-tab-label">生产者</span>' +
		'</a>' +
		'<a id="cut_cd_3" class="mui-tab-item"  href="'+APP.web_root+'goods/goods.html?foot_active=3">' +
		'<i class="mui-icon iconfont icon-chanpin"></i>' +
		'<span class="mui-tab-label">产品</span>' +
		'</a>' +
		'<a id="cut_cd_4" class="mui-tab-item"  href="'+APP.web_root+'member/member_index.html?foot_active=4">' +
		'<i class="mui-icon iconfont icon-yonghu"></i>' +
		'<span class="mui-tab-label">我的</span>' +
		'</a></nav>');

	for(var i = 1; i <= 4; i++) {
		if(chai == i) {
			$("#cut_cd_" + i).addClass("mui-tab-item mui-active");
		} else {
			$("#cut_cd_" + i).addClass("mui-tab-item");
		}

	}
}
//登录判断
function dlpd(){
	var member=JSON.parse(localStorage.getItem("member"));	
		if(!member){
			layer.msg('请登录',{icon:2,time:1500,shade: 0.1});
			window.location.href="../login.html";    	
		}
}



//图片转化为缩略图路径
function toThumb(pic) {
	var i = pic.lastIndexOf("."); //点的位置
	var postfix = pic.substr(i, pic.length); //后缀
	var thumb = pic.substr(0, i) + "_thumb" + postfix;
	return thumb;
}

function del_event() {
	var del = ca.className('del');
	for(var a = 0; a < del.length; a++) {
		del[a].addEventListener('tap', function() {
			$(this).parent().parent().parent().find('.file-btn').show();
			$(this).parent().remove();
		})
	}
}
/**
 * 上传图片
 * name 存储图片form元素id
 * length 上传张数
 */

	//获取多张图片路径
	var img='0';

function readFile(input, name, length,tol) {
	var img_list = $(input).parent().parent().find("div[id='img_list']");
	if(input.files && input.files[0]) {
		var reader = new FileReader();
		var fd = new FormData();
		for(var i = 0; i < input.files.length; i++) {
			var reader = new FileReader();
			console.log(input.files[i]);
			reader.readAsDataURL(input.files[i]);
			fd.append(i, input.files[i]);　　　　
		}
		$.ajax({
			url: APP.api_url + "System/upload",
			type: 'POST',
			data: fd,
			async: false,
			cache: false,
			contentType: false,
			processData: false,
			success: function(returndata) {
				var res=JSON.parse(returndata).files[0].url;
					img++;
					if(tol == 10){
						var img_url1=res.substr(2, res.length);
	              	var innerHTML = '<div class="images-item">' +
					'	<span class="del">×</span>' +
					'	<img style="width: 90%;height: 150px; margin:0 auto;" src="' + APP.pic_url + img_url1 + '"/>' +
					'	<input calss="pic'+img+'" type="hidden" name="pic_d" value="'+img_url1+'" />'+
					'	<input id="p" type="hidden" name="'+name+'1" value="'+img+'" />'+
					'</div>';
					img_list.append(innerHTML);
					del_event();
					}else{
						var img_url1=res.substr(2, res.length);
	              	var innerHTML = '<div class="images-item">' +
					'	<span class="del">×</span>' +
					'	<img style="width: 80px;height: 80px; margin:0 auto;" src="' + APP.pic_url + img_url1 + '"/>' +
					'	<input id="pic'+img+'" type="hidden" name="'+name+'" value="'+img_url1+'" />'+
					'	<input id="p" type="hidden" name="'+name+'1" value="'+img+'" />'+
					'</div>';
					img_list.append(innerHTML);
					del_event();
					if(img_list.find('.images-item').size() >= length){
						$(input).parent(".file-btn").hide();
					}
					}
	               	
			},
			error: function(data) {
				alert('no');
			}
		});
	} else {
		alert("抱歉，你的浏览器不支持 FileReader");
	}
}



/**
 * url参数获取
 * @param  name 参数名
 */
function getUrlParam(pname) {
	var name, value;
	var str = location.href; //取得整个地址栏
	var num = str.indexOf("?")
	str = str.substr(num + 1); //取得所有参数   stringvar.substr(start [, length ]
	var arr = str.split("&"); //各个参数放到数组里
	for(var i = 0; i < arr.length; i++) {
		num = arr[i].indexOf("=");
		if(num > 0) {
			name = arr[i].substring(0, num);
			value = arr[i].substr(num + 1);
			if(pname == name) {
				return value;
			}
		}
	}
}
/**
 * 新增url中参数值
 */
function setParam(param,value){
    var query = location.search.substring(1);
    var p = new RegExp("(^|)" + param + "=([^&]*)(|$)");
    if(p.test(query)){
        //query = query.replace(p,"$1="+value);
        var firstParam=query.split(param)[0];
        var secondParam=query.split(param)[1];
        if(secondParam.indexOf("&")>-1){
            var lastPraam=secondParam.split("&")[1];
            return  '?'+firstParam+'&'+param+'='+value+'&'+lastPraam;
        }else{
            if(firstParam){
                return '?'+firstParam+'&'+param+'='+value;
            }else{
                return '?'+param+'='+value;
            }
        }
    }else{
        if(query == ''){
            return '?'+param+'='+value;
        }else{
            return '?'+query+'&'+param+'='+value;
        }
    }
}
/**
 * 修改url中参数的值
 */
function replaceParamVal(paramName,replaceWith) {
    var oUrl = this.location.href.toString();
    var re=eval('/('+ paramName+'=)([^&]*)/gi');
    var nUrl = oUrl.replace(re,paramName+'='+replaceWith);
    this.location = nUrl;
}

//更新用户localstorm
function update_Member(member) {
	localStorage.setItem('member', JSON.stringify(member));
}
//获得当前登录用户ID
function getUid() {
	var member = JSON.parse(localStorage.getItem('member'));
	return member['id'];
}
//获取保存用户的某个属性信息
function getValueByName(name){
	var member = JSON.parse(localStorage.getItem('member'));
	return member[name];
}
function checkLogin(url) {
	var member = JSON.parse(localStorage.getItem('member'));
	if(member == null) {
		window.location.href = url;
	}else{
		return member;
	}
}

//检查用户登录,登陆后跳回源页面
function back_login(){
	//检查用户登录
	var user = JSON.parse(localStorage.getItem('member'));
		if(!user){
			layer.msg('请先登录！', {time: 1000}, function() {
				addcookie('source_page',location.href);
				location.href='/member/login.html';
				});
		}else{
			return true;
		}
}


function getUserMobile() {
	var member = JSON.parse(localStorage.getItem('member'));
	return member['mobile'];
}



//简单页面跳转
function url_jump(data, url) {
	layer.msg(data.msg, {
		icon: 1,
		time: 1000 //2秒关闭（如果不配置，默认是3秒）
	}, function() {
		if(data.code == 200) {
			location.href = url + '.html';
		}
	});
}

//页面跳转
function url_data(data) {
	ca.newInterface({
		url: data + '.html',
		id: data,
	});
}

//获取用户token
function get_token() {
	var member = JSON.parse(localStorage.getItem('member'));
	return member['token'];
}

function login_jump(url) {
	var login_user = getUid();
	if(!login_user) {
		ca.prompt('请先登录');
		setTimeout(function() {
			url_jump("login");
		}, 1000);
	} else {
		url_jump(url);
	}
}
